import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:riverpod_t/base/base_grid_view.dart';
import 'package:riverpod_t/base/empty_widget.dart';
import 'package:riverpod_t/base/error_river_widget.dart';
import 'package:riverpod_t/base/loading_widget.dart';
import 'package:riverpod_t/page/home/router/home_router.dart';
import 'package:riverpod_t/page/home/widget/car_toon_widget.dart';
import 'package:riverpod_t/page/mine/river/mine_list_river.dart';
import 'package:riverpod_t/page/mine/state/mine_state.dart';
import 'package:riverpod_t/until/app_util.dart';
import '../../../base/base_stateful_page.dart';

///  ref.refresh
///  ref.invalidate
///  skipLoadingOnRefresh: true,
///  skipLoadingOnReload: true,
///  AsyncValue.guard

class MinePage extends BasePage {
  const MinePage({super.key});

  @override
  BasePageState<BasePage> getState() => _MinePageState();
}

class _MinePageState extends BasePageState<MinePage> {
  /// 列表控制器
  final ScrollController scrollController = ScrollController();

  /// 刷新组建控制器
  final RefreshController refreshController = RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    super.appBarTitle = '我的';
    allowBackNavigation = false;
  }

  @override
  Widget buildLeftButton() {
    return const SizedBox();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  Widget _listBody(BuildContext context, MineState state, WidgetRef ref) {
    if (AppUtil.isEmpty(state.list)) return EmptyWidget();
    return BaseGridView(
      enablePullDown: true,
      enablePullUp: true,
      // onRefresh: () => ref.read(mineListRiverProvider.notifier).refresh(isRefresh: true),
      onRefresh: () => ref.refresh(mineListRiverProvider.future),
      onLoading: () => ref.read(mineListRiverProvider.notifier).refresh(),
      refreshController: refreshController,
      scrollController: scrollController,
      data: state.list,
      padding: EdgeInsets.all(10.h),
      childAspectRatio: 0.7,
      crossAxisSpacing: 10.w,
      mainAxisSpacing: 10.h,
      crossAxisCount: 2,
      backgroundColor: const Color(0xFFF3F4F8),
      itemBuilder: (context22, index) {
        return CarTonWidget(
          index: index,
          model: state.list[index],
          onTap: () {
            HomeNavigator.toHomeDetailPage(context, imageUrl: state.list[index].image ?? '');
          },
        );
      },
    );
  }

  void _listenOpChange(AsyncValue<MineState>? previous, AsyncValue<MineState> next) {
    if (next.value?.loadFinish == true) {
      refreshController.refreshCompleted();
      refreshController.loadComplete();
    }
    if (next.value?.hasNext == false) {
      refreshController.loadNoData();
    }
  }

  @override
  Widget buildPage(BuildContext context) {
    return Consumer(
      builder: (BuildContext context, WidgetRef ref, Widget? child) {
        ref.listen(mineListRiverProvider, (p, n) => _listenOpChange(p, n));
        return ref
            .watch(mineListRiverProvider)
            .when(
              skipLoadingOnRefresh: true,
              skipLoadingOnReload: true,
              skipError: false,
              data: (state) {
                return _listBody(context, state, ref);
              },
              error:
                  (error, stack) =>
                      ErrorRiverWidget(type: ErrorPageType.component, refreshMethod: () => {}),
              loading: () => LoadingWidget(),
            );
      },
    );
  }
}
